package com.jhgsys.internal.workflow.controller;

import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.workflow.dto.WorkflowSaveRequestDto;
import com.jhgsys.internal.workflow.entity.WorkflowInfo;
import com.jhgsys.internal.workflow.service.IWorkflowInfoService;
import com.jhgsys.internal.workflow.service.IWorkflowNodeService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 流程信息表 Controller
 *
 * @author fenghaijun
 * @date 2024-07-15 17:34:52
 */
@Slf4j
@Validated
@Controller
public class WorkflowInfoController extends BaseController {

    @Autowired
    private IWorkflowInfoService workflowInfoService;

    @Autowired
    private IWorkflowNodeService workflowNodeService;


    @GetMapping(FebsConstant.VIEW_PREFIX + "workflowInfo")
    @RequiresPermissions("workflowInfo:view")
    public String workflowInfoIndex(Model model) {
        model.addAttribute("hasHeadCompanyRole",hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId",getCurrentTenantId());
        return FebsUtil.view("workflow/workflowInfo/workflowInfoList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "workflowInfo/add")
    @RequiresPermissions("workflowInfo:view")
    public String workflowInfoAdd() {
        return FebsUtil.view("workflow/workflowInfo/workflowInfoEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "workflowInfo/update/{id}")
    @RequiresPermissions("workflowInfo:view")
    public String workflowInfoUpdate(Model model, @PathVariable("id") String id) {
        model.addAttribute("workflowInfo", workflowInfoService.findWorkflowInfoById(id));
        model.addAttribute("userInfo",getCurrentUser());
        return FebsUtil.view("workflow/workflowInfo/workflowInfoEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "workflowInfo/detail/{workflowId}")
    @RequiresPermissions("workflowInfo:view")
    public String workflowInfoDetail(Model model, @PathVariable("workflowId") String workflowId) {
        model.addAttribute("workflowInfo", workflowInfoService.findWorkflowInfoById(workflowId));
        return FebsUtil.view("workflow/workflowInfo/workflowInfoDetail");
    }

    /**
     * 查询（所有）
     *
     * @author fenghaijun
     * @date 2024-07-15 17:34:52
     */
    @GetMapping("workflowInfo")
    @ResponseBody
    @RequiresPermissions("workflowInfo:view")
    public FebsResponse getAllWorkflowInfos(WorkflowInfo workflowInfo) {
        return new FebsResponse().success().data(workflowInfoService.findWorkflowInfos(workflowInfo));
    }

    /**
     * 查询（分页）
     *
     * @author fenghaijun
     * @date 2024-07-15 17:34:52
     */
    @GetMapping("workflowInfo/list")
    @ResponseBody
    @RequiresPermissions("workflowInfo:view")
    public FebsResponse workflowInfoList(QueryRequest request, WorkflowInfo workflowInfo) {
        //非超管访问时添加TenantId
        if(StringUtils.isBlank(workflowInfo.getTenantId())){
            workflowInfo.setTenantId(getCurrentTenantId());
        }
        Map<String, Object> dataTable = getDataTable(this.workflowInfoService.findWorkflowInfos(request, workflowInfo));
        return new FebsResponse().success().data(dataTable);
    }


    /**
     * 逻辑删除 WorkflowInfo
     *
     * @author fenghaijun
     * @date 2024-07-15 17:34:52
     */
    @Log("逻辑删除工作流程")
    @GetMapping("workflowInfo/delete/{id}")
    @ResponseBody
    @RequiresPermissions("workflowInfo:view")
    public FebsResponse deleteWorkflowInfo(@PathVariable("id") String workflowInfoIds) throws FebsException {
        try {
            WorkflowInfo workflowInfo = new WorkflowInfo();
            workflowInfo.setDeletedBy(getCurrentUser().getUserName());
            workflowInfo.setDeletedTime(new Date());
            workflowInfo.setDeletedFlg(FebsConstant.INVALID);
            this.workflowInfoService.deleteWorkflowInfo(workflowInfo, workflowInfoIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除工作流程失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 物理删除 WorkflowInfo
     *
     * @author fenghaijun
     * @date 2024-07-15 17:34:52
     */
    @Log("物理删除工作流程")
    @GetMapping("workflowInfo/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("workflowInfo:view")
    public FebsResponse physicallyDeleteWorkflowInfo(@PathVariable("id") String workflowInfoIds) throws FebsException {
        try {
            this.workflowInfoService.physicallyDeleteWorkflowInfo(workflowInfoIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除工作流程失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 新增保存流程信息
     */
    @Log("保存工作流程")
    @PostMapping("workflowInfo/save")
    @ResponseBody
    public FebsResponse save(@RequestBody WorkflowSaveRequestDto workflowSaveRequest) throws FebsException {
        try {
            workflowSaveRequest.setUserName(getCurrentUser().getUserName());
            workflowInfoService.workflowSave(workflowSaveRequest);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "保存工作流程失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 导出 WorkflowInfo的excel
     *
     * @author fenghaijun
     * @date 2024-07-15 17:34:52
     */
    @PostMapping("workflowInfo/excel")
    @ResponseBody
    @RequiresPermissions("workflowInfo:view")
    public void export(QueryRequest queryRequest, WorkflowInfo workflowInfo, HttpServletResponse response) throws FebsException {
        try {
            List<WorkflowInfo> workflowInfos = this.workflowInfoService.findWorkflowInfos(queryRequest, workflowInfo).getRecords();
            ExcelKit.$Export(WorkflowInfo.class, response).downXlsx(workflowInfos, false);
        } catch (Exception e) {
            String message = "导出工作流程失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 更新流程状态
     *
     * @author fenghaijun
     * @date 2024-07-15 17:34:52
     */
    @Log("更新流程状态")
    @ResponseBody
    @PostMapping("workflowInfo/updateStatus")
    public FebsResponse update(@RequestBody WorkflowInfo workflowInfo) throws FebsException {
        try {
            WorkflowInfo update = new WorkflowInfo();
            update.setWorkflowId(workflowInfo.getWorkflowId());
            update.setWorkflowStatus(workflowInfo.getWorkflowStatus());
            update.setUpdatedBy(getCurrentUser().getUserName());
            this.workflowInfoService.updateWorkflowInfo(workflowInfo);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "更新流程状态失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 根据workflowName查询对应的节点
     *
     * @author fenghaijun
     * @date 2024-07-15 17:34:52
     */
    @GetMapping("workflowInfo/getNodeByWorkflowName")
    @ResponseBody
    public FebsResponse getNodeByWorkflowName(String workflowId) throws Exception {
        try {

            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "获取业务节点失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }
}
